namespace ChangeFileName;

public partial class Form1 : Form
{
    private string oldName;
    private string newName;
    
    public Form1()
    {
        InitializeComponent();
        UpdateButtonState();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        using (FolderBrowserDialog fbd = new FolderBrowserDialog())
        {
            // 设置初始目录（可选）
            fbd.RootFolder = Environment.SpecialFolder.Desktop;
        
            if (fbd.ShowDialog() == DialogResult.OK)
            {
                var selectedPath = fbd.SelectedPath;
                try
                {
                    // 获取文件夹中所有 Excel 文件
                    var excelFiles = Directory.GetFiles(selectedPath)
                        .Where(file => 
                            Path.GetExtension(file).Equals(".xls", StringComparison.OrdinalIgnoreCase) ||
                            Path.GetExtension(file).Equals(".xlsx", StringComparison.OrdinalIgnoreCase))
                        .ToArray();
                    
                    if (excelFiles.Length == 0)
                    {
                        MessageBox.Show("未找到符合条件的文件！");
                        return;
                    }
                    MessageBox.Show("请选择要导出的文件夹！");
                    // 选择目标文件夹
                    using (FolderBrowserDialog exportDialog = new FolderBrowserDialog())
                    {
                        exportDialog.Description = "选择导出文件夹";
                        if (exportDialog.ShowDialog() == DialogResult.OK)
                        {
                            string targetFolder = exportDialog.SelectedPath;
                            ProcessAndExportFiles(excelFiles, targetFolder);
                        }
                    }
                }
                catch (Exception ex)
                {
                    // 捕获并处理异常（如权限不足、路径无效等）
                    Console.WriteLine("读取文件时出错：" + ex.Message);
                }
            }
        }
    }

    private void ProcessAndExportFiles(string[] sourceFiles, string targetFolder)
    {
        foreach (string sourceFile in sourceFiles)
        {
            try
            {
                // 提取原始文件名（不含路径）
                string originalFileName = Path.GetFileName(sourceFile);
            
                // 仅替换第一个匹配的 oldName
                int index = originalFileName.IndexOf(oldName, StringComparison.Ordinal);
                if (index >= 0)
                {
                    string prefix = originalFileName.Substring(0, index);
                    string suffix = originalFileName.Substring(index + oldName.Length);
                    string newFileName = prefix + newName + suffix;
                
                    string targetFilePath = Path.Combine(targetFolder, newFileName);
                    File.Copy(sourceFile, targetFilePath, overwrite: true);
                
                    Console.WriteLine($"文件导出成功：{newFileName}");
                }
                else
                {
                    // 若未找到 oldName，直接跳过或保留原文件名
                    string targetFilePath = Path.Combine(targetFolder, originalFileName);
                    File.Copy(sourceFile, targetFilePath, overwrite: true);
                    Console.WriteLine($"未找到匹配项，保留原文件名：{originalFileName}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"处理文件 {sourceFile} 时出错：{ex.Message}");
            }
        }
        MessageBox.Show("文件导出完成！");
    }
    
    private void UpdateButtonState()
    {
        // 判断两个变量是否为空（或仅空格）
        var isOldNameValid = !string.IsNullOrWhiteSpace(oldName);
        var isNewNameValid = !string.IsNullOrWhiteSpace(newName);

        // 更新按钮状态
        button1.Enabled = isOldNameValid && isNewNameValid;
    }
    
    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        oldName = textBox1.Text;
        UpdateButtonState();
    }

    private void textBox2_TextChanged(object sender, EventArgs e)
    {
        newName = textBox2.Text;
        UpdateButtonState();
    }
}